package com.itzz.spring_zhoneHeng.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itzz.spring_zhoneHeng.dao.UserDao;
import com.itzz.spring_zhoneHeng.pojo.Module;
import com.itzz.spring_zhoneHeng.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
//自定义的登录逻辑
//  此为创建类后 最开始的第一步
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    UserDao userDao;
    @Autowired
    PasswordEncoder pw;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("拦截逻辑");
        //根据用户名查询用户的账号 加密密码  所有的权限
//        if(!"admin".equals(username)){
//            throw  new UsernameNotFoundException("用户名不存在");
//        }
        //根据用户名查询用户信息 如果放回数据为null 则抛出异常用户名不存在
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",username);
        User user = userDao.selectOne(userQueryWrapper);
        if(user==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //根据用户名查询用户拥有的所有权限集合
        List<Module> roles = userDao.getRole(username);
        //将这些权限集合添加到  User中的权限集合对象中
        ArrayList<GrantedAuthority> authorities=new ArrayList<>();
        roles.forEach(role->{
            authorities.add(new SimpleGrantedAuthority(role.getRole()));
        });
//        for (Module module : role) {
//            authorities.add(new SimpleGrantedAuthority(module.getRole()));
//        }
        //再将用户数据保存到UserDetails中
        System.out.println(username);
        System.out.println(user.getPassword());
//        String encode = pw.encode("123");
//        System.out.println(encode);



//        //模拟加密
//        String encode = pw.encode("123");
        //账号名    加密密码                   权限集合
        return new User(user.getPath(),username,user.getPassword(),authorities);


//        return new User(username,encode,
//                AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal,user,ROLE_a"));
    }
}
